package com.lincoln.framework.service;

import com.lincoln.framework.entity.Setting;
import com.lincoln.framework.hibernate.SimpleHibernateTemplate;
import com.lincoln.framework.utils.ParameterChecker;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 分类
 * Created by Lincoln on 2017/10/18.
 */
@Service
@Transactional
public class SettingService extends BaseService<Setting>{
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        dao = new SimpleHibernateTemplate<>(sessionFactory, Setting.class);
    }

    public Criteria createCriteria(Criteria criteria, Map<String, Object> parameters) {
        if (!ParameterChecker.isNullOrEmpty((String)parameters.get("key"))) {
            criteria.add(Restrictions.like("key", "%" + (String)parameters.get("key") + "%"));
        }
        return criteria;
    }

    /**
     * 校验是否存在
     *
     * @return boolean
     */
    public boolean checkExist(int id, String key) {
        Criteria criteria = this.dao.createCriteria();
        if (id > 0) {
            return getById(id) != null;
        }
        criteria.add(Restrictions.eq("key", key));
        return this.dao.findByCriteria(criteria).size() > 0;
    }

    /**
     * 通过key查询
     * @param key
     * @return
     */
    public Setting findByKey(String key){
        Criteria criteria = this.dao.createCriteria();
        criteria.add(Restrictions.eq("key", key));
        List<Setting> list =  this.dao.findByCriteria(criteria);
        if(list == null||list.size()<=0){
            return null;
        }else{
            return list.get(0);
        }
    }
    /**
     * 保存
     */
    public void save(String key,String value) {
        Setting setting = findByKey(key);
        if(setting == null){
            setting = new Setting();
            setting.setKey(key);
            setting.setCreateTime(new Date());
        }
        setting.setValue(value);
        setting.setUpdateTime(new Date());
        this.dao.save(setting);
    }
}
